package com.hyacinth.utils.file;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 解压缩数据工具类
 * Reason:
 * date: 2016年9月2日 下午1:24:25
 * @since JDK 1.6
 */
public class FlaterUtil {

	/**
	 * compress:压缩
	 * @param data
	 */
	public static byte[] compress(byte[] data) {
		byte[] output = new byte[0];
		Deflater df = new Deflater();
		df.reset();
		df.setInput(data);
		df.finish();
		ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
		try {
			byte[] buf = new byte[1024];
			while (!df.finished()) {
				int i = df.deflate(buf);
				o.write(buf, 0, i);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			output = data;
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		df.end();
		return output;
	}

	/**
	 * decompress:解压
	 * @param data
	 */
	public static byte[] decompress(byte[] data) {
		byte[] output = new byte[0];
		Inflater inf = new Inflater();
		inf.reset();
		inf.setInput(data);
		ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
		try {
			byte[] buf = new byte[1024];
			while (!inf.finished()) {
				int i = inf.inflate(buf);
				o.write(buf, 0, i);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			output = data;
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		inf.end();
		return output;
	}
}
